package com.stockz.ui.swing.charting.painter.indicator;

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;

import com.stockz.indicator.vsa.VsaBar;
import com.stockz.indicator.vsa.pattern.VsaPattern;
import com.stockz.indicator.vsa.pattern.VsaPatternType;
import com.stockz.ui.swing.charting.display.indicator.VolumeSpreadAnalysis;
import com.stockz.ui.swing.charting.util.MathUtil;
import com.stockz.ui.swing.charting.view.StockChartPanelState;
import com.stockz.ui.swing.charting.view.StockRectangle;

public class VsaIndicatorPainter {

	private static double textPadding = 0;
	
	public static void paint(Graphics2D g, VolumeSpreadAnalysis indicatorDisplay) {
		
		StockRectangle rectangle = indicatorDisplay.getRectangle();
		if (rectangle != null && !rectangle.isEmpty()) {
			
			VolumeSpreadAnalysis vsaIndicatorDisplay = (VolumeSpreadAnalysis)indicatorDisplay;
			List<VsaBar> vsaBarList = vsaIndicatorDisplay.getVsaBarList();
			
			StockChartPanelState state = indicatorDisplay.getStockChartPanel().getStockChartPanelState();
			
			double textHeight = g.getFont().getStringBounds("A", g.getFontRenderContext()).getHeight();
			
			for (int i = state.getEndIndex() - 1; i >= state.getStartIndex(); i--) {
				
				int X = MathUtil.fitX(
						rectangle.x, 
						state.getTimeUnitSpace(),
						state.getEndIndex(), 
						i);

				int bullishCount = 0;
				int bearishCount = 0;
				
				int Y = 0;
				
				for(VsaPattern vsaPattern : vsaBarList.get(i).getVsaPatternList()){
					if(VsaPatternType.Bullish.equals(vsaPattern.getVsaPatternType())
							|| VsaPatternType.Undefined.equals(vsaPattern.getVsaPatternType())){
						g.setColor(Color.GREEN);
						
						if(VsaPatternType.Undefined.equals(vsaPattern.getVsaPatternType())){
							g.setColor(Color.BLUE);
						}
						
						Y = MathUtil.fitY(
								rectangle.y,
								rectangle.y + rectangle.height,
								state.getMinimumPriceVisible(),
								state.getMaximumPriceVisible(), 
								state.getBarList().get(i).getLow(),
								state.isSemiLog());
						bullishCount ++;
						Y += bullishCount*textHeight + textPadding;
					}else if(VsaPatternType.Bearish.equals(vsaPattern.getVsaPatternType())){
						g.setColor(Color.RED);
						Y = MathUtil.fitY(
								rectangle.y,
								rectangle.y + rectangle.height,
								state.getMinimumPriceVisible(),
								state.getMaximumPriceVisible(), 
								state.getBarList().get(i).getHigh(),
								state.isSemiLog());
						Y -= (bearishCount*textHeight + textPadding);
						bearishCount++;					
					}
					
					String shortName = vsaPattern.getShortName();
					double textWidth = g.getFont().getStringBounds(shortName, g.getFontRenderContext()).getWidth(); 
					int x = (int)(X - textWidth/2);
					
					g.drawString(vsaPattern.getShortName(), x, Y);
				}				
			}
		}
	}
}
